/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CentralServerApplication.java
 *
 * Created on Sep 4, 2011, 11:48:20 PM
 */
package central.server.gui;

import central.server.CentralServer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JOptionPane;
import share.TimerLabel;

/**
 *
 * @author mire
 */
public class CentralServerApplication extends javax.swing.JFrame {

    /** Creates new form CentralServerApplication */
    public CentralServerApplication() {
        initComponents();

        this.centralServer = null;
        redirectSystemStreams();

        //Center frame
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension size = this.getSize();
        screenSize.height = screenSize.height / 2;
        screenSize.width = screenSize.width / 2;
        size.height = size.height / 2;
        size.width = size.width / 2;
        int y = screenSize.height - size.height;
        int x = screenSize.width - size.width;
        this.setLocation(x, y);
    }

    private void setServerOnline() {
        centralServerAddressLabel.setEnabled(true);
        centralServerAddress.setText(centralServer.getAddress());

        centralServerStatus.setText("Подигнут");
        centralServerStatus.setForeground(Color.green);

        Integer port = centralServer.getOperatorPort();
        centralServerOperatorPortLabel.setEnabled(true);
        centralServerOperatorPort.setText(port.toString());

        Integer aliveTimeout = centralServer.getAliveTimeout();
        centralServerAliveTimeoutLabel.setEnabled(true);
        centralServerAliveTimeout.setText(aliveTimeout.toString());

        centralServerStatusTimer.setEnabled(true);
        ((TimerLabel) centralServerStatusTimer).start();

        operatorsTabs = new CentralServerOperatorsTabs(centralServer.getOperators(), jTabbedPane, redirectedScrollPane.getSize());
        operatorsTabs.start();

        (new Thread(centralServer)).start();
    }

    private void updateTextArea(final String text) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                redirectedTextArea.append(text);
            }
        });
    }

    private void redirectSystemStreams() {
        OutputStream out = new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                updateTextArea(String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                updateTextArea(new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };

        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        authorDialog = new javax.swing.JDialog();
        authorAvatarLabel = new javax.swing.JLabel();
        authorNameLabel = new javax.swing.JLabel();
        authorIndexLabel = new javax.swing.JLabel();
        authorMailLabel = new javax.swing.JLabel();
        startDialog = new javax.swing.JDialog();
        startOperatorPortTextField = new javax.swing.JFormattedTextField();
        startOperatorPortLabel = new javax.swing.JLabel();
        startButtonOK = new javax.swing.JButton();
        startButtonCancel = new javax.swing.JButton();
        startAliveTimeoutLabel = new javax.swing.JLabel();
        startAliveTimeoutTextField = new javax.swing.JFormattedTextField();
        centralServerStatusLabel = new javax.swing.JLabel();
        centralServerOperatorPortLabel = new javax.swing.JLabel();
        centralServerAliveTimeoutLabel = new javax.swing.JLabel();
        centralServerOperatorPort = new javax.swing.JLabel();
        centralServerAliveTimeout = new javax.swing.JLabel();
        centralServerStatus = new javax.swing.JLabel();
        centralServerStatusTimer = new TimerLabel();
        jSeparator1 = new javax.swing.JSeparator();
        centralServerAddressLabel = new javax.swing.JLabel();
        centralServerAddress = new javax.swing.JLabel();
        jTabbedPane = new javax.swing.JTabbedPane();
        redirectedScrollPane = new javax.swing.JScrollPane();
        redirectedTextArea = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        startMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        aboutMenuItem = new javax.swing.JMenuItem();

        authorDialog.setTitle("О аутору");
        authorDialog.setMinimumSize(new java.awt.Dimension(410, 150));
        authorDialog.setResizable(false);

        authorAvatarLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/share/icons/avatar_100.png"))); // NOI18N

        authorNameLabel.setFont(new java.awt.Font("Courier New", 1, 18));
        authorNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        authorNameLabel.setText(" Мирко Француски");

        authorIndexLabel.setFont(new java.awt.Font("Courier New", 1, 18));
        authorIndexLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        authorIndexLabel.setText(" 225/06");

        authorMailLabel.setFont(new java.awt.Font("Courier New", 1, 18));
        authorMailLabel.setForeground(new java.awt.Color(0, 0, 255));
        authorMailLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        authorMailLabel.setText(" fm060225d@student.etf.rs");

        javax.swing.GroupLayout authorDialogLayout = new javax.swing.GroupLayout(authorDialog.getContentPane());
        authorDialog.getContentPane().setLayout(authorDialogLayout);
        authorDialogLayout.setHorizontalGroup(
            authorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(authorDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(authorAvatarLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(authorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(authorIndexLabel)
                    .addComponent(authorMailLabel)
                    .addComponent(authorNameLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        authorDialogLayout.setVerticalGroup(
            authorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(authorDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(authorDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(authorDialogLayout.createSequentialGroup()
                        .addComponent(authorNameLabel)
                        .addGap(18, 18, 18)
                        .addComponent(authorIndexLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(authorMailLabel))
                    .addComponent(authorAvatarLabel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        authorDialog.setLocationRelativeTo(rootPane);

        startDialog.setTitle("Покретање централног сервера");
        startDialog.setAlwaysOnTop(true);
        startDialog.setMinimumSize(new java.awt.Dimension(288, 170));

        startOperatorPortLabel.setText("Операторски порт");

        startButtonOK.setText("У реду");
        startButtonOK.setMaximumSize(new java.awt.Dimension(102, 25));
        startButtonOK.setMinimumSize(new java.awt.Dimension(102, 25));
        startButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonOKActionPerformed(evt);
            }
        });

        startButtonCancel.setText("Одустани");
        startButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonCancelActionPerformed(evt);
            }
        });

        startAliveTimeoutLabel.setText("Време провере");

        javax.swing.GroupLayout startDialogLayout = new javax.swing.GroupLayout(startDialog.getContentPane());
        startDialog.getContentPane().setLayout(startDialogLayout);
        startDialogLayout.setHorizontalGroup(
            startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, startDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(startDialogLayout.createSequentialGroup()
                        .addComponent(startButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(startButtonCancel))
                    .addGroup(startDialogLayout.createSequentialGroup()
                        .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(startOperatorPortLabel)
                            .addComponent(startAliveTimeoutLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                        .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(startOperatorPortTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(startAliveTimeoutTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        startDialogLayout.setVerticalGroup(
            startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(startDialogLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startOperatorPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(startOperatorPortLabel))
                .addGap(18, 18, 18)
                .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startAliveTimeoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(startAliveTimeoutLabel))
                .addGap(38, 38, 38)
                .addGroup(startDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(startButtonOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(startButtonCancel))
                .addContainerGap(20, Short.MAX_VALUE))
        );

        startDialog.setLocationRelativeTo(rootPane);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Централни сервер");

        centralServerStatusLabel.setFont(new java.awt.Font("Dialog", 1, 14));
        centralServerStatusLabel.setText("Статус");

        centralServerOperatorPortLabel.setLabelFor(centralServerOperatorPort);
        centralServerOperatorPortLabel.setText("Глобални порт");
        centralServerOperatorPortLabel.setEnabled(false);

        centralServerAliveTimeoutLabel.setLabelFor(centralServerAliveTimeout);
        centralServerAliveTimeoutLabel.setText("Време провере");
        centralServerAliveTimeoutLabel.setEnabled(false);

        centralServerOperatorPort.setForeground(new java.awt.Color(0, 0, 255));
        centralServerOperatorPort.setText("          ");

        centralServerAliveTimeout.setForeground(new java.awt.Color(0, 0, 255));
        centralServerAliveTimeout.setText("           ");

        centralServerStatus.setFont(new java.awt.Font("Dialog", 1, 14));
        centralServerStatus.setForeground(new java.awt.Color(255, 0, 0));
        centralServerStatus.setText("Угашен");
        centralServerStatus.setToolTipText("");

        centralServerStatusTimer.setFont(new java.awt.Font("Dialog", 1, 14));
        centralServerStatusTimer.setText("00:00:00");
        centralServerStatusTimer.setEnabled(false);

        centralServerAddressLabel.setFont(new java.awt.Font("Dialog", 1, 14));
        centralServerAddressLabel.setText("Моја адреса");
        centralServerAddressLabel.setEnabled(false);

        centralServerAddress.setFont(new java.awt.Font("Dialog", 1, 14));
        centralServerAddress.setForeground(new java.awt.Color(0, 0, 255));
        centralServerAddress.setText("        ");

        redirectedTextArea.setColumns(20);
        redirectedTextArea.setEditable(false);
        redirectedTextArea.setRows(5);
        redirectedScrollPane.setViewportView(redirectedTextArea);

        jTabbedPane.addTab("Излаз", redirectedScrollPane);

        fileMenu.setMnemonic('f');
        fileMenu.setText("Мени");

        startMenuItem.setMnemonic('o');
        startMenuItem.setText("Старт");
        startMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(startMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Излаз");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("Помоћ");

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("Аутор");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(centralServerStatusLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(centralServerStatus))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(centralServerAddressLabel)
                        .addGap(46, 46, 46)
                        .addComponent(centralServerAddress)))
                .addGap(85, 85, 85)
                .addComponent(centralServerStatusTimer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 249, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(centralServerAliveTimeoutLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(centralServerAliveTimeout))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(centralServerOperatorPortLabel)
                        .addGap(41, 41, 41)
                        .addComponent(centralServerOperatorPort)))
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 801, Short.MAX_VALUE)
            .addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 801, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(centralServerAddressLabel)
                            .addComponent(centralServerAddress))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(centralServerStatusLabel)
                            .addComponent(centralServerStatus)
                            .addComponent(centralServerStatusTimer)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(centralServerOperatorPort)
                            .addComponent(centralServerOperatorPortLabel))
                        .addGap(14, 14, 14)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(centralServerAliveTimeout)
                            .addComponent(centralServerAliveTimeoutLabel))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
    authorDialog.setVisible(true);
}//GEN-LAST:event_aboutMenuItemActionPerformed

private void startMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startMenuItemActionPerformed
    if (CentralServer.existsConfugration()) {
        centralServer = new CentralServer();
        setServerOnline();
    } else {
        startDialog.setVisible(true);
    }
    startMenuItem.setEnabled(false);
}//GEN-LAST:event_startMenuItemActionPerformed

private void startButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonOKActionPerformed
    startDialog.setVisible(false);

    int operatorPort = 0;
    int aliveTimeout = 0;

    try {
        operatorPort = Integer.parseInt(startOperatorPortTextField.getText());
        aliveTimeout = Integer.parseInt(startAliveTimeoutTextField.getText());
        if (operatorPort == 0 || aliveTimeout == 0) {
            throw new NumberFormatException();
        }
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(this, "Погрешно унтети параметри", "Грешка", JOptionPane.ERROR_MESSAGE);
        startDialog.setVisible(true);
        return;
    }
    centralServer = new CentralServer(operatorPort, aliveTimeout);
    setServerOnline();
}//GEN-LAST:event_startButtonOKActionPerformed

private void startButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonCancelActionPerformed
    startDialog.setVisible(false);
    startMenuItem.setEnabled(true);
    startOperatorPortTextField.setText(null);
    startAliveTimeoutTextField.setText(null);
}//GEN-LAST:event_startButtonCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new CentralServerApplication().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JLabel authorAvatarLabel;
    private javax.swing.JDialog authorDialog;
    private javax.swing.JLabel authorIndexLabel;
    private javax.swing.JLabel authorMailLabel;
    private javax.swing.JLabel authorNameLabel;
    private javax.swing.JLabel centralServerAddress;
    private javax.swing.JLabel centralServerAddressLabel;
    private javax.swing.JLabel centralServerAliveTimeout;
    private javax.swing.JLabel centralServerAliveTimeoutLabel;
    private javax.swing.JLabel centralServerOperatorPort;
    private javax.swing.JLabel centralServerOperatorPortLabel;
    private javax.swing.JLabel centralServerStatus;
    private javax.swing.JLabel centralServerStatusLabel;
    private javax.swing.JLabel centralServerStatusTimer;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JScrollPane redirectedScrollPane;
    private javax.swing.JTextArea redirectedTextArea;
    private javax.swing.JLabel startAliveTimeoutLabel;
    private javax.swing.JFormattedTextField startAliveTimeoutTextField;
    private javax.swing.JButton startButtonCancel;
    private javax.swing.JButton startButtonOK;
    private javax.swing.JDialog startDialog;
    private javax.swing.JMenuItem startMenuItem;
    private javax.swing.JLabel startOperatorPortLabel;
    private javax.swing.JFormattedTextField startOperatorPortTextField;
    // End of variables declaration//GEN-END:variables
    private CentralServer centralServer;
    private CentralServerOperatorsTabs operatorsTabs;
}
